3.14 排名统计
Excel中的排名函数是rank(),而pandas中也是rank()函数,并且有更多的排名方式,
rank()函数ascending参考默认是True,也就是默认为升序排序,
rank()函数的method参数提供了对相同值的5种处理方法,如下:
常量 | 注释 |
---|---|
Average | 默认值,对相同值做平均排名 |
Min | 对相同值做最小的排名 |
Max | 对相同值做最大的排名 |
First | 对相同值出现的顺序排名 |
Dense | 与最小排名类似,但不同名次之间差值为1 |
import pandas as pd
df=pd.read_excel(r "D:\Pyobject2023\object\测试\素材\测试素材.考试成绩.总分排名.xlsx" )
print (df)
df[ "中式排名" ]=df[ "总分" ].rank( method = "dense" , ascending =False).astype( int )
df[ "中式排名1" ]=df[ "总分" ].rank( method = "dense" , ascending =True).astype( int )
df[ "美式排名" ]=df[ "总分" ].rank( method = "min" , ascending =False).astype( int )
print (df)
返回:
姓名 | 数学 | 语文 | 英语 | 总分 | |
---|---|---|---|---|---|
0 | 小明 | 50.0 | 99 | 84 | 233.0 |
1 | 小张 | 100.0 | 100 | 98 | 298.0 |
2 | 小王 | 93.0 | 55 | 6 | 154.0 |
3 | 小李 | 18.5 | 95 | 99 | 212.5 |
4 | 小四 | 90.0 | 9 | 71 | 170.0 |
5 | 小管 | 100.0 | 66 | 5 | 170.0 |
姓名 | 数学 | 语文 | 英语 | 总分 | 中式排名 | 中式排名1 | 美式排名 | |
---|---|---|---|---|---|---|---|---|
0 | 小明 | 50.0 | 99 | 84 | 233.0 | 2 | 4 | 2 |
1 | 小张 | 100.0 | 100 | 98 | 298.0 | 1 | 5 | 1 |
2 | 小王 | 93.0 | 55 | 6 | 154.0 | 5 | 1 | 6 |
3 | 小李 | 18.5 | 95 | 99 | 212.5 | 3 | 3 | 3 |
4 | 小四 | 90.0 | 9 | 71 | 170.0 | 4 | 2 | 4 |
5 | 小管 | 100.0 | 66 | 5 | 170.0 | 4 | 2 | 4 |